package pingpongdojo.mygames;

import java.text.SimpleDateFormat;
import java.util.List;

import org.eclipse.jface.dialogs.IMessageProvider;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.jface.layout.TableColumnLayout;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.ui.PlatformUI;

import pingpongdojo.model.Game;
import pingpongdojo.model.Game.Objective;
import pingpongdojo.model.ModelFactory;
import pingpongdojo.model.User;
import pingpongdojo.newgame.NewGameHandler;

public class MyGamesDialog extends TitleAreaDialog {

	public static final String ID = "pingpongdojo.mygames.MyGamesDialog";

	protected class GameSelectionListener implements Listener {
		private Table table;

		public GameSelectionListener(Table table) {
			this.table = table;
		}

		public void handleEvent(Event e) {
			TableItem selectedItem = table.getItem(table.getSelectionIndex());
			selectedGame = (Game) selectedItem.getData();
			okButton.setEnabled(selectedGame != null);
		}
	}

	private Game selectedGame;

	private Button okButton;

	// private Logger logger = Logger.getLogger(MyGamesDialog.class.getName());

	public MyGamesDialog(Shell parentShell) {
		super(parentShell);
	}

	public Game getSelectedGame() {
		return selectedGame;
	}

	@Override
	public void create() {
		super.create();

		setTitle("PingPong Dojo: My Games");
		setMessage("Select a game to resume", IMessageProvider.INFORMATION);
	}

	@Override
	protected Control createDialogArea(Composite parent) {
		GridLayout layout = new GridLayout();
		layout.numColumns = 1;
		parent.setLayout(layout);

		GridData gridData = new GridData();
		gridData.grabExcessHorizontalSpace = true;
		gridData.horizontalAlignment = GridData.FILL;

		final TabFolder tabFolder = new TabFolder(parent, SWT.BORDER);
		tabFolder.setLayoutData(gridData);

		tabFolder.addSelectionListener(new SelectionListener() {
			public void widgetSelected(SelectionEvent e) {
				okButton.setEnabled(false);
			}

			public void widgetDefaultSelected(SelectionEvent e) {
				widgetSelected(e);
			}
		});

		List<Game> activeGames = ModelFactory.getInstance().getGameManager()
				.getActiveGames();

		if (activeGames.size() > 0) {
			TabItem activeGamesTab = new TabItem(tabFolder, SWT.NULL);
			activeGamesTab.setText("Active");
			activeGamesTab.setControl(createActiveGamesTab(tabFolder));
		} else {
			createPlaceHolderTab("Active", "No active games", tabFolder);
		}

		createPlaceHolderTab("Pending", "Feature not implemented.", tabFolder);
		createPlaceHolderTab("Completed", "Feature not implemented.", tabFolder);

		return parent;
	}

	protected void createPlaceHolderTab(String label, String text,
			TabFolder tabFolder) {
		TabItem tabItem = new TabItem(tabFolder, SWT.NULL);
		tabItem.setText(label);
		Label textLabel = new Label(tabFolder, SWT.BORDER);
		textLabel.setText(text);
		tabItem.setControl(textLabel);
	}

	protected Control createActiveGamesTab(Composite parent) {
		User currentUser = ModelFactory.getInstance().getUserManager()
				.getCurrentUser();

		List<Game> activeGames = ModelFactory.getInstance().getGameManager()
				.getActiveGames();

		GridData gridData = new GridData();
		gridData.grabExcessHorizontalSpace = true;
		// gridData.grabExcessVerticalSpace = true;
		gridData.horizontalAlignment = GridData.FILL;
		// gridData.verticalAlignment = GridData.FILL;

		Composite composite = new Composite(parent, SWT.NONE);
		composite.setLayoutData(gridData);

		Table gamesTable = new Table(composite, SWT.BORDER | SWT.V_SCROLL);
		gamesTable.addListener(SWT.Selection, new GameSelectionListener(
				gamesTable));

		TableColumn tableColumn1 = new TableColumn(gamesTable, SWT.LEFT);
		tableColumn1.setText("Name");

		TableColumn tableColumn2 = new TableColumn(gamesTable, SWT.CENTER);
		tableColumn2.setText("Partner");

		TableColumn tableColumn3 = new TableColumn(gamesTable, SWT.CENTER);
		tableColumn3.setText("Objective");

		TableColumn tableColumn4 = new TableColumn(gamesTable, SWT.CENTER);
		tableColumn4.setText("Last played");

		TableColumn tableColumn5 = new TableColumn(gamesTable, SWT.CENTER);
		tableColumn5.setText("Status");

		TableColumnLayout columnLayout = new TableColumnLayout();
		composite.setLayout(columnLayout);

		columnLayout.setColumnData(tableColumn1, new ColumnWeightData(30));
		columnLayout.setColumnData(tableColumn2, new ColumnWeightData(30));
		columnLayout.setColumnData(tableColumn3, new ColumnWeightData(20));
		columnLayout.setColumnData(tableColumn4, new ColumnWeightData(40));
		columnLayout.setColumnData(tableColumn5, new ColumnWeightData(20));

		gamesTable.setHeaderVisible(true);
		gamesTable.setLinesVisible(true);

		SimpleDateFormat df = new SimpleDateFormat();
		for (Game game : activeGames) {
			TableItem item = new TableItem(gamesTable, SWT.NONE);
			item.setData(game);

			User otherPlayer = game.getOtherPlayer(currentUser);
			Objective currentUserObjective = game.getObjective(currentUser);

			item.setText(new String[] { game.getName(), otherPlayer.getName(),
					game.getCurrentObjective().name(),
					df.format(game.getDateLastPlayed()),
					game.getStatus().name() });
		}

		return composite;
	}

	@Override
	protected void createButtonsForButtonBar(Composite parent) {
		GridData gridData = new GridData();
		gridData.verticalAlignment = GridData.FILL;
		gridData.horizontalSpan = 3;
		gridData.grabExcessHorizontalSpace = true;
		gridData.grabExcessVerticalSpace = true;
		gridData.horizontalAlignment = SWT.CENTER;

		parent.setLayoutData(gridData);

		this.okButton = createOkButton(parent, OK, "Resume Game", true);
		okButton.setEnabled(false);

		Button cancelButton = createButton(parent, CANCEL, "Cancel", false);

		cancelButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				setReturnCode(CANCEL);
				close();
			}
		});

		Button newGameButton = createNewGameButton(parent);
	}

	protected Button createOkButton(Composite parent, int id, String label,
			boolean defaultButton) {
		((GridLayout) parent.getLayout()).numColumns++;
		Button button = new Button(parent, SWT.PUSH);
		button.setText(label);
		button.setFont(JFaceResources.getDialogFont());
		button.setData(new Integer(id));
		button.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent event) {
				okPressed();
			}
		});
		if (defaultButton) {
			Shell shell = parent.getShell();
			if (shell != null) {
				shell.setDefaultButton(button);
			}
		}
		setButtonLayoutData(button);
		return button;
	}

	protected Button createNewGameButton(Composite parent) {
		((GridLayout) parent.getLayout()).numColumns++;
		Button button = new Button(parent, SWT.PUSH);
		button.setText("New Game");
		button.setFont(JFaceResources.getDialogFont());
		button.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent event) {
				setReturnCode(CANCEL);
				close();

				NewGameHandler.showDialog(PlatformUI.getWorkbench()
						.getActiveWorkbenchWindow());
			}
		});

		setButtonLayoutData(button);
		return button;
	}

	@Override
	protected boolean isResizable() {
		return false;
	}

	@Override
	protected void okPressed() {
		super.okPressed();
	}

}